package cn.sany.cterminal.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理类
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 返回的Map对象会被@ResponseBody注解转换为JSON数据返回
     * @return
     */
    public static final String DEFAULT_ERROR_VIEW = "forward:/error.html";
    // @ExceptionHandler用来定义函数针对的异常类型，最后将Exception对象和请求URL映射到error.html中
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
        log.info("进入异常页面");
        ModelAndView mav = new ModelAndView() ;
        mav.addObject("errorname", "统一异常处理页面") ;
        mav.addObject("exception", e) ;
        mav.addObject("url", request.getRequestURL()) ;
        mav.setViewName(DEFAULT_ERROR_VIEW) ;
        return mav ;
    }
}